package com.gjintel.framework.dict.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.dict.model.Dictionary;
import com.gjintel.framework.dict.service.IDictService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.dto.TreeDto;
import com.gjintel.sdk.util.StringUtil;

@RequestMapping("/framework/dict")
@Controller
public class DictController {
	private static final Logger LOG = Logger.getLogger(DictController.class);
	@Autowired
	private IDictService dictService;

	/**
	 * @description 根据ID对当前的操作进行控制（ID为空，代表当前是添加操作，ID不为空，代表当前是更新操作）
	 * @author fengya
	 * @date 2015-7-23 上午10:54:10
	 * @param id
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/input")
	public ModelAndView input(String id) {
		ModelAndView mv = new ModelAndView("/framework/dict/dict-input");
		Dictionary dict = null;
		if (!StringUtil.isEmpty(id)) {
			dict = (Dictionary) InitCacheData.getInstance().getCacheData(CacheType.DICT).get(id);
			if (!StringUtil.isEmpty(dict.getPid())) {
				Object obj = InitCacheData.getInstance().getCacheData(CacheType.DICT).get(dict.getPid());
				if (obj != null) {
					Dictionary pDict = (Dictionary) obj;
					dict.setpName(pDict == null ? "" : pDict.getName());
				}
			}
			mv.addObject("dict", dict);
		}
		return mv;
	}

	/**
	 * @方法名：getDictionaryTree
	 * @功能说明：得到机构树
	 * @author fengya
	 * @date 2014-4-26 下午04:07:36
	 * @return JSONObject
	 */
	@RequestMapping("/getDictionaryTreeDialog")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject getDictionaryTreeDialog(String id, String nodeName, String deleteIds) {
		// 树中节点所在的集合
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		try {
			if (nodeName != null) {
				nodeName = URLDecoder.decode(nodeName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			LOG.debug("汉字转换错误！", e);
		}
		Map jsonData = new HashMap();
		// 查询到的节点ID的集合
		List<String> selIds = this.dictService.getDictionaryTree(treeList, id, nodeName, deleteIds, true);
		jsonData.put("selIds", JSONArray.fromObject(selIds));
		jsonData.put("tree", JSONArray.fromObject(treeList));
		return JSONObject.fromObject(jsonData);
	}

	/**
	 * @description 根据节点ID，得到节点下所有的子孩子信息
	 * @author fengya
	 * @date 2015-7-23 上午11:00:19
	 * @param id
	 * @return
	 * @return JSONObject
	 */
	@RequestMapping("/getDictionaryTree")
	@ResponseBody
	public JSONArray getDictionaryTree(String id) {
		// 树中节点所在的集合
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		this.dictService.getDictionaryTree(treeList, id, null, null, false);
		return JSONArray.fromObject(treeList);
	}

	/**
	 * @方法名：list
	 * @功能说明：根据查询条件获得消息类型记录
	 * @author fengya
	 * @date 2014-5-30 下午04:39:36
	 * @return void
	 */
	@RequestMapping("/list")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject list(Page page, Dictionary dict, Sort sort) {
		this.dictService.findAll(page, dict, sort);
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @方法名：save
	 * @功能说明：保存记录数据
	 * @author fengya
	 * @date 2014-5-30 上午09:28:49
	 * @return void
	 * @throws Exception
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpSession session, Dictionary dict) {
		User user = (User) session.getAttribute("loginUser");
		if (dict != null) {
			boolean sign = false;
			if (StringUtil.isEmpty(dict.getId())) {
				dict.setId(null);
				dict.setCreateTime(new Date());
				dict.setCreaterId(user.getId());
				dict.setCreaterName(user.getName());
				sign = true;
			}
			if (dict.getDisSort() == null) {
				dict.setDisSort(0);
			}
			dict.setUpdaterName(user.getName());
			dict.setUpdaterId(user.getId());
			dict.setUpdateTime(new Date());
			this.dictService.saveOrUpdate(dict);
			if (sign) {
				LogUtil.addLog(new LogInfo("添加数据字典数据", user.getId(), user.getName(), String.valueOf(LogType.ADD.ordinal()), dict.getClass().getSimpleName(), dict.getId()));
			} else {
				LogUtil.addLog(new LogInfo("更新数据字典数据", user.getId(), user.getName(), String.valueOf(LogType.UPDATE.ordinal()), dict.getClass().getSimpleName(), dict.getId()));
			}
			InitCacheData.getInstance().initDictData();
			return Constant.SAVE_SUCCESS;
		}
		return Constant.SAVE_UN_SUCCESS;
	}

	/**
	 * @方法名：remove
	 * @功能说明：根据选择的记录进行删除数据
	 * @author fengya
	 * @date 2014-4-17 下午04:13:04
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public String remove(HttpSession session, String deleteIds) {
		this.dictService.removeData(deleteIds);
		User user = (User) session.getAttribute("loginUser");
		LogUtil.addLog(new LogInfo("删除数据字典数据", user.getId(), user.getName(), String.valueOf(LogType.DELETE.ordinal()), Dictionary.class.getSimpleName(), deleteIds));
		InitCacheData.getInstance().initData();
		return Constant.DEL_SUCCESS;
	}
}
